package com.ldk.admin.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ldk.admin.common.ResponseResult;
import com.ldk.admin.constants.CONFIG;
import com.ldk.admin.constants.FORM;
import com.ldk.admin.constants.SESSION;
import com.ldk.framework.entity.*;
import com.ldk.framework.service.*;

import org.apache.commons.lang.StringUtils;
import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import com.ldk.admin.common.LigerUIGridResult;
import com.ldk.admin.constants.ViewMode;
import com.ldk.base.framework.common.CustomPageable;
import com.ldk.base.framework.util.SystemUtil;
import com.ldk.framework.enums.PlatformUserType;

import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * A.4.7、车辆基本信息
 *
 * @author xiangwl
 * 2018年8月9日
 * com.ldk.admin.controller
 * VehicleController
 */
@Controller
@RequestMapping("/baseinfo")
public class VehicleController extends BaseController {
    /**
     * 路由地址
     */
    private final String route = "baseinfo";
    /**
     * 模块名称
     */
    private final String module = "车辆基本信息";
    @Autowired
    private IVehicleService vehicleService;
    @Autowired
    private ICompanypermitService companypermitService;

    @RequestMapping("/vehicle/list")
    public ModelAndView edit(ModelMap map, HttpServletRequest request,
                             HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);

        setLinks(map, "", "", module + "管理", "/" + route + "/vehicle/list", "添加" + module, "/" + route + "/vehicle/add");
        map.addAttribute("route", route);
        map.addAttribute("module", module);
        map.addAttribute("companyList", getCompanyList());

        return new ModelAndView("/baseinfo/vehicle/list");
    }

    @ResponseBody
    @RequestMapping("/vehicle/getList")
    public LigerUIGridResult<Vehicle> getList(@RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                              @RequestParam(value = "pagesize", required = false, defaultValue = "10") int pageSize,
                                              @RequestParam(value = "companyId", required = false, defaultValue = "") String companyId,
                                              @RequestParam(value = "searchKey", required = false, defaultValue = "") String searchKey,
                                              HttpServletRequest request) {
        int limit = pageSize;
        int offset = (page - 1) * pageSize;

        Vehicle query = new Vehicle();
        if (!StringUtils.isBlank(companyId)) {
            query.setCompanyId(companyId);
        }

        AdminUser admin = (AdminUser) request.getSession().getAttribute(SESSION.USER);
        if (admin != null && admin.getRoleId() == CONFIG.COMPANY_ROLEID) {
            query.setCompanyId(admin.getCompanyId());
        }

        if (!StringUtils.isBlank(searchKey)) {
            query.setSearchKey(searchKey);
        }
        CustomPageable pageable = new CustomPageable(offset, limit);

        Page<Vehicle> result = vehicleService.selectPageList("", query, pageable);

        LigerUIGridResult<Vehicle> grid = new LigerUIGridResult<>();
        grid.Total = result.getTotalElements();
        grid.Rows = result.getContent();

        return grid;
    }

    @RequestMapping("/vehicle/add")
    public ModelAndView add(ModelMap map, HttpServletRequest request,
                            HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        setLinks(map, module + "管理", "/" + route + "/vehicle/list", "添加" + module, "/" + route + "/vehicle/add", "", "");
        setForm(map, "/" + route + "/vehicle/insert", null);
        map.addAttribute("module", module);
        map.addAttribute("companyList", getCompanyList());
        Vehicle model = new Vehicle();

        return new ModelAndView("/baseinfo/vehicle/info", "model", model);
    }

    @RequestMapping("/vehicle/edit/{id}")
    public ModelAndView edit(@PathVariable long id, ModelMap map, HttpServletRequest request,
                             HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        Vehicle query = new Vehicle();
        query.setId(id);

        Vehicle model = vehicleService.selectOne("", query);
        if (model == null) {
            return new ModelAndView("redirect:/" + route + "/vehicle/list");
        }
        setLinks(map, module + "管理", "/" + route + "/vehicle/list", "编辑" + module, "/" + route + "/vehicle/edit/" + id, "", "");
        setForm(map, "/" + route + "/vehicle/update", null);
        map.addAttribute("module", module);
        map.addAttribute("companyList", getCompanyList());

        return new ModelAndView("/baseinfo/vehicle/info", "model", model);
    }

    @RequestMapping("/vehicle/insert")
    public ModelAndView insert(@ModelAttribute("model") Vehicle model,
                               RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
                               HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        ResponseResult rst = new ResponseResult();
        redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
        try {
            if (model.getEnabled() == null) {
                model.setEnabled(false);
            }
            if(TextUtils.isEmpty(model.getVehicleNo())){
                rst.AddError("添加" + module + "失败,车牌号码不能为空");
                return new ModelAndView("redirect:/" + route + "/vehicle/add");
            }
            model.setDatetime(SystemUtil.getAllSeconds());
            int row = vehicleService.insert("", model);
            if (row > 0) {
                rst.AddOk("添加" + module + "成功");
            } else {
                rst.AddError("添加" + module + "失败");
            }
        } catch (Exception e) {
            rst.AddError("添加" + module + "失败");
            logger.error(e.getMessage());
        }
        return new ModelAndView("redirect:/" + route + "/vehicle/add");
    }

    @RequestMapping("/vehicle/update")
    public ModelAndView update(@ModelAttribute("model") Vehicle model,
                               RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
                               HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        ResponseResult rst = new ResponseResult();

        redAttr.addAttribute("id", model.getId());
        redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
        try {
            if (model.getEnabled() == null) {
                model.setEnabled(false);
            }
            int row = vehicleService.updateByKey("", model);
            if (row > 0) {
                rst.AddOk("修改" + module + "成功");
            } else {
                rst.AddError("修改" + module + "失败");
            }
        } catch (Exception e) {
            rst.AddError("修改" + module + "失败");
            logger.error(e.getMessage());
        }

        return new ModelAndView("redirect:/" + route + "/vehicle/edit/{id}");
    }

    /**
     * 浏览
     *
     * @param id
     * @param map
     * @return
     */
    @RequestMapping("/vehicle/view/{id}")
    public ModelAndView view(@PathVariable long id, ModelMap map, HttpServletRequest request,
                             HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);

        setViewMode(map, ViewMode.View);
        Vehicle query = new Vehicle();
        query.setId(id);
        Vehicle model = vehicleService.selectOne("", query);

        map.addAttribute("module", module);

        return new ModelAndView("/baseinfo/vehicle/info", "model", model);
    }

    @ResponseBody
    @RequestMapping("/vehicle/remove/{id}")
    public ResponseResult remove(@PathVariable long id, HttpServletRequest request) {

        ResponseResult rst = new ResponseResult();
        if (id < 1) {
            rst.AddError("删除" + module + "错误");
            return rst;
        }
        Boolean successed = false;
        try {
            Vehicle query = new Vehicle();
            query.setId(id);
            int row = vehicleService.deleteByKey("", query);
            successed = row > 0;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (successed) {
            rst.AddOk("删除" + module + "成功");
        } else {
            rst.AddError("删除" + module + "失败");
        }

        return rst;
    }

    /**
     * 获取分公司列表
     *
     * @return
     */
    private List<Companypermit> getCompanyList() {
        Companypermit query = new Companypermit();
        query.setEnabled(true);

        return companypermitService.selectList("", query);
    }
}
